import { analyzeModifiedLines, isLineInAIRanges } from "./diff-analyzer.js"
import { execSync } from "child_process"
import axios from 'axios';

function main() {
  const { meta, files } = analyzeModifiedLines();
  const records = [];

  // 遍历文件生成记录
  Object.entries(files).forEach(([filePath, { chunks, aiRanges }]) => {
    let totalLines = 0;
    let aiLines = 0;

    chunks.forEach(chunk => {
      const chunkContent = execSync(
        `git show HEAD:${filePath} | sed -n ${chunk.start},${chunk.start + chunk.lineCount - 1}p`
      ).toString().split('\n');

      for (let i = 0; i < chunk.lineCount; i++) {
        const lineNum = chunk.start + i;
        const lineContent = chunkContent[i] || '';

        if (lineContent.trim() === '' || lineContent.match(/^\s*(\/\/|#|\/\*|\*)/)) {
          continue; // 直接跳过，不计数
        }
    
        totalLines++; // 只统计非空、非注释的有效代码行
    
        // 检查是否是 AI 生成的行
        if (isLineInAIRanges(lineNum, aiRanges)) {
          aiLines++;
        }
      }
    });

    if (totalLines > 0) {
      records.push({
        ...meta,
        file_path: filePath,
        total_lines: totalLines,
        ai_lines: aiLines,
        ai_ratio: parseFloat((aiLines / totalLines * 100).toFixed(2))
      });
    }
  });

  // 输出控制台报表
  console.table(records.map(r => ({
    '文件': r.file_path,
    '总行数': r.total_lines,
    'AI行数': r.ai_lines,
    'AI占比%': r.ai_ratio,
    '作者': r.email
  })));
  try {
    axios
    .post('http://h9c7644451.goho.co/ai/aiStats', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: {
            records
        }
    })
    .then((res) => {
        console.log('📤 数据上报成功');
    });
  } catch (error) {
    console.error('⚠️ 上报失败:', error.message);
  }
}

main()